//
//  RegisterVC.m
//  phmall
//
//  Created by admin on 2017/9/20.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "RegisterVC.h"
#import "Register2VC.h"
@interface RegisterVC ()<UITextFieldDelegate>
{
    UITextField *name;
    UITextField *passWord;
    UITextField *confirm;
    UIButton    *show;
    UIButton    *showC;
    UIButton    *next;
    UIButton    *_available;
    BOOL        nameYN;
}
@property(nonatomic,strong)SocketIOClient *client;
@end

@implementation RegisterVC
-(void)viewWillAppear:(BOOL)animated{
     [super viewWillAppear:animated];
      [self connection];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.client disconnect];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    if ([self.type isEqualToString:@"new"]) {
        self.title=Localized(@"新用户注册");
    }
    if ([self.type isEqualToString:@"google"]) {
        self.title=@"绑定google账号";
    }
    if ([self.type isEqualToString:@"facebook"]) {
        self.title=@"绑定facebook账号";
    }
    nameYN=NO;
    [self setUI];
    // Do any additional setup after loading the view.
}
- (void)connection{
    
    [self.client on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        NSLog(@"*************\n\niOS客户端上线\n\n*************");
    }];
    [self.client on:@"check_id" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) {
        NSString *available=[NSString stringWithFormat:@"%@", event?event[0]:@""];
        if ([available isEqualToString:@"0"]) {
            nameYN=YES;
            [_available setImage:[UIImage imageNamed:@"用户名正确"] forState:UIControlStateNormal];
        }else{
            nameYN=NO;
            [_available setImage:[UIImage imageNamed:@"用户名错误或已被注册"] forState:UIControlStateNormal];
        }
    }];
    [self.client on:@"error" callback:^(NSArray * _Nonnull event, SocketAckEmitter * _Nonnull ack) {
        NSLog(@"*************\n\n%@\n\n*************",event?event[0]:@"");
        nameYN=NO;
        [_available setImage:[UIImage imageNamed:@"用户名错误或已被注册"] forState:UIControlStateNormal];
//        [self.client connect];
    }];
    [self.client connect];
    
}
-(void)rightBarAction{
    
}
-(void)setUI{
    UIBarButtonItem *rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"帮助中心"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIBarButtonItem *leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    UIImageView *logo=[[UIImageView alloc]init];
    [self.view addSubview:logo];

    logo.image=[UIImage imageNamed:@"logo"];
    ViewBorderRadius(logo, 10, 0, [UIColor whiteColor]);
    [logo mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset((218-RectStatus.size.height-44-64));
        make.centerX.equalTo(self.view);
        make.width.height.offset(70);
    }];
    
    name=[[UITextField alloc]init];
    name.delegate=self;
    name.placeholder=Localized(@"用户名");
    name.font=[UIFont systemFontOfSize:18];
    name.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [self.view addSubview:name];
    [name mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.right.equalTo(self.view.mas_right).with.offset(-60);
        make.top.equalTo(logo.mas_bottom).with.offset(20);
        make.height.offset(40);
    }];
    [name addTarget:self action:@selector(textField1TextChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    _available=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_available];
    _available.userInteractionEnabled=NO;
     [_available setImage:[UIImage imageNamed:@"用户名错误或已被注册"] forState:UIControlStateNormal];
    [_available mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(name.mas_right);
        make.centerY.equalTo(name);
        make.width.height.offset(24);
    }];
    
    
    UIView *nameLine=[[UILabel alloc]init];
    [self.view addSubview:nameLine];
    nameLine.backgroundColor=[UIColor orangeColor];
    [nameLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(name.mas_bottom);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];
    
    passWord=[[UITextField alloc]init];
    passWord.placeholder=Localized(@"密码");
    passWord.delegate=self;
    passWord.font=[UIFont systemFontOfSize:18];
    passWord.secureTextEntry = YES;
    [self.view addSubview:passWord];
    passWord.keyboardType=UIKeyboardTypeASCIICapable;
    [passWord mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.right.equalTo(self.view.mas_right).with.offset(-60);
        make.top.equalTo(name.mas_bottom).with.offset(30);
        make.height.offset(40);
    }];
    
    show=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:show];
    [show setImage:[UIImage imageNamed:@"密码显示-未点击输入框"] forState:UIControlStateNormal];
    [show setImage:[UIImage imageNamed:@"隐藏密码-未点击输入框"] forState:UIControlStateSelected];
    [show addTarget:self action:@selector(showPassWord:) forControlEvents:UIControlEventTouchUpInside];
    [show mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passWord.mas_right);
        make.centerY.equalTo(passWord);
        make.width.height.offset(24);
    }];
    
    UIView *passLine=[[UILabel alloc]init];
    [self.view addSubview:passLine];
    passLine.backgroundColor=[UIColor orangeColor];
    [passLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passWord.mas_bottom);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];

    confirm=[[UITextField alloc]init];
    confirm.placeholder=Localized(@"确认密码");
    confirm.secureTextEntry = YES;
    confirm.delegate=self;
    confirm.keyboardType=UIKeyboardTypeASCIICapable;
    confirm.font=[UIFont systemFontOfSize:18];
    [self.view addSubview:confirm];
    [confirm mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.right.equalTo(self.view.mas_right).with.offset(-60);
        make.top.equalTo(passWord.mas_bottom).with.offset(30);
        make.height.offset(40);
    }];
    
    showC=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:showC];
    [showC setImage:[UIImage imageNamed:@"密码显示-未点击输入框"] forState:UIControlStateNormal];
    [showC setImage:[UIImage imageNamed:@"隐藏密码-未点击输入框"] forState:UIControlStateSelected];
    [showC addTarget:self action:@selector(showPassWord:) forControlEvents:UIControlEventTouchUpInside];
//    密码显示-未点击输入框   隐藏密码-输入内容后 隐藏密码-未点击输入框 密码显示-输入内容后
    [showC mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(confirm.mas_right);
        make.centerY.equalTo(confirm);
        make.width.height.offset(24);
    }];
    
    UIView *confirmLine=[[UILabel alloc]init];
    [self.view addSubview:confirmLine];
    confirmLine.backgroundColor=[UIColor orangeColor];
    [confirmLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(confirm.mas_bottom);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];
    
    next=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:next];
    [next setTitle:Localized(@"下一步") forState:UIControlStateNormal];
    [next addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [next setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    next.backgroundColor=[UIColor colorWithHexString:@"#ff9300"];
    ViewBorderRadius(next, 5, 0, [UIColor colorWithHexString:@"#ff9300"]);
    [next setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
    [next mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(confirm.mas_bottom).with.offset(50);
        make.height.offset(44);
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
    }];
}
-(void)showPassWord:(UIButton *)but{
    if (but==show) {
        show.selected=!show.selected;
    }else{
        showC.selected=!showC.selected;
    }
    if (show.selected) {
         passWord.secureTextEntry = NO;
    }else{
        passWord.secureTextEntry = YES;
    }
    if (showC.selected) {
        confirm.secureTextEntry = NO;
    }else{
        confirm.secureTextEntry = YES;
    }
}
-(void)nextAction{
    if (!nameYN) {
        NSLog(@"用户名不可用或格式错误");
        [PublicClass ProgressHUDModeText:@"用户名不可用或格式错误" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"用户名不可用或格式错误"];
        return;
    }
    if (passWord.text.length==0||name.text==nil) {
        NSLog(@"密码不可为空");
        [PublicClass ProgressHUDModeText:@"密码不可为空" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"密码不可为空"];
        return;
    }
    if (confirm.text.length==0||name.text==nil) {
        NSLog(@"密码不可为空");
        [PublicClass ProgressHUDModeText:@"密码不可为空" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"密码不可为空"];
        return;
    }
    if (passWord.text.length>18||passWord.text.length<6) {
        NSLog(@"密码长度控制在6-18位");
        [PublicClass ProgressHUDModeText:@"密码长度控制在6-18位" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"密码长度控制在6-18位"];
    }
    if ([self judgePassWordLegal:passWord.text]) {
        NSLog(@"密码格式错误");
        [PublicClass ProgressHUDModeText:@"密码格式错误" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"密码格式错误"];
        return;
    }
    if (![passWord.text isEqualToString:confirm.text]) {
        NSLog(@"两次密码不同");
        [PublicClass ProgressHUDModeText:@"两次密码不同" andTime:2];
//        [SVProgressHUD showErrorWithStatus:@"两次密码输入不同"];
        return;
    }

    Register2VC *regis=[[Register2VC alloc]init];
    regis.type=self.type;
    regis.name=name.text;
    regis.pass=passWord.text;
    [self.navigationController pushViewController:regis animated:YES];
    
}
- (BOOL)validateUserName:(NSString *)name{
    NSString *userNameRegex = @"^(?![0-9]+$)[0-9A-Za-z]{4,16}$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return !B;
}
-(BOOL)judgePassWordLegal:(NSString *)pass{
    BOOL result = false;
    if ([pass length] >= 8){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return !result;
}
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

//    return YES;
//}// return NO to not change text
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField==passWord) {
        [show setImage:[UIImage imageNamed:@"密码显示-输入内容后"] forState:UIControlStateNormal];
        [show setImage:[UIImage imageNamed:@"隐藏密码-输入内容后"] forState:UIControlStateSelected];
    }
    if (textField==confirm) {
        [showC setImage:[UIImage imageNamed:@"密码显示-输入内容后"] forState:UIControlStateNormal];
        [showC setImage:[UIImage imageNamed:@"隐藏密码-输入内容后"] forState:UIControlStateSelected];
    }
}// became first responder

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField==passWord) {
        [show setImage:[UIImage imageNamed:@"密码显示-未点击输入框"] forState:UIControlStateNormal];
        [show setImage:[UIImage imageNamed:@"隐藏密码-未点击输入框"] forState:UIControlStateSelected];
    }
    if (textField==confirm) {
        [showC setImage:[UIImage imageNamed:@"密码显示-未点击输入框"] forState:UIControlStateNormal];
        [showC setImage:[UIImage imageNamed:@"隐藏密码-未点击输入框"] forState:UIControlStateSelected];
    }
}// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
-(void)textField1TextChange:(UITextField *)textField{
    if (textField==name&&textField.text.length!=0) {
        if ([self validateUserName:name.text]) {
            nameYN=NO;
            [_available setImage:[UIImage imageNamed:@"用户名错误或已被注册"] forState:UIControlStateNormal];
        }else{
            [self.client emit:@"check_id" with:@[textField.text]];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (SocketIOClient *)client{
    if (!_client) {
        NSURL* url = [[NSURL alloc] initWithString:HomeURL];
        _client = [[SocketIOClient alloc] initWithSocketURL:url config:@{@"log": @YES, @"forcePolling": @YES}];
    }
    return _client;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
